package com.zpark.dao.impl;

import com.zpark.dao.IAccountDao;
import com.zpark.pojo.Account;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 持久层接口实现类
 */
@Repository
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    Logger log = Logger.getLogger(AccountDaoImpl.class.getName());

    @Override
    public List<Account> selectAll() {
        log.info("开始查询所有数据...");
        String sql = "select id, uid, money from account";
        log.info(sql);
        List<Account> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Account.class));

        log.info("查询所有数据结束...\n" + query);
        return query;
    }

    @Override
    public Account selectById(Integer id) {
        String sql = "select id, uid, money from account where id=?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class), id);
    }

    @Override
    public Integer insert(Account account) {
        String sql = "insert into account(uid, money) values(?, ?)";
        return jdbcTemplate.update(sql, account.getUid(), account.getMoney());
    }

    @Override
    public Integer update(Account account) {
        String sql = "update account set uid=?, money=? where id=?";
        return jdbcTemplate.update(sql, account.getUid(), account.getMoney(), account.getId());
    }

    @Override
    public Integer delete(Integer id) {
        String sql = "delete from account where id=?";
        return jdbcTemplate.update(sql, id);
    }
}
